package master.support;

import master.common.pk.LongTimePKGenerator;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;

import javax.persistence.Column;
import javax.persistence.Id;
import java.beans.PropertyDescriptor;

/**
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 */
public abstract class DomainObject implements JSONAware {

    @Id
    @Column(name = "ID")
    private long id;

    /**
     * 新建 DomainObject，并设置好必要的值，比如：Id
     *
     * @param domainObjectClass
     * @param <T>
     * @return
     */
    public static <T extends DomainObject> T newDomainObject(Class<T> domainObjectClass) {
        try {
            T domainObject = domainObjectClass.newInstance();
            domainObject.setId(LongTimePKGenerator.getInstance().nextLongId());
            return domainObject;
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public DomainObject() {

    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public JSONObject toJSONObject(){
        JSONObject jsonObject = new JSONObject();

        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
        for (PropertyDescriptor propertyDescriptor : bw.getPropertyDescriptors()) {
            if(propertyDescriptor.getName().equals("class")) {
                continue;
            }
            jsonObject.put(propertyDescriptor.getName(), bw.getPropertyValue(propertyDescriptor.getName()));
        }
        return jsonObject;

    }

    @SuppressWarnings("unchecked")
	public final String toJSONString() {
        return toJSONObject().toJSONString();
    }
}
